package com.itany.shop.service.impl;

import com.itany.shop.dao.UserDao;
import com.itany.shop.entity.User;
import com.itany.shop.exception.RequestParameterException;
import com.itany.shop.exception.UserExistException;
import com.itany.shop.exception.UserNotExistException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.UserService;
import com.itany.shop.util.MD5Util;
import com.itany.shop.util.ParamterUtil;

/**
 * @author MissChen
 * @version 1.0
 * @date 2023 年12月20日 15:11
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao= (UserDao) ObjectFactory.getObject("userDao");
    @Override
    public void register(String username, String password, String phone, String address) throws RequestParameterException, UserExistException {
        if(ParamterUtil.isNull(username) || ParamterUtil.isNull(password) ||ParamterUtil.isNull(phone) ||ParamterUtil.isNull(address) ){
                throw new RequestParameterException("参数有误");
        }
        User selectUser=userDao.selectByUsername(username);

        //用户已经存在，抛出异常
        if(selectUser!=null){
            throw new UserExistException("用户名已经存在");
        }

        User user=new User(username, MD5Util.md5(password),phone,address);
        //调用dao中的insertUser()
        userDao.insertUser(user);
    }

    @Override
    public User login(String username, String password) throws RequestParameterException, UserNotExistException {
        if(ParamterUtil.isNull(username) ||ParamterUtil.isNull(password)){
            throw new RequestParameterException("请求参数有误");
        }
        User user=userDao.selectUserByUsernameAndPassword(username,MD5Util.md5(password));
        if(null==user){
            throw new UserNotExistException("用户名或者密码错误");
        }
        return user;
    }
}
